<template>
  <div>
    <el-checkbox
      :value="todoObj.done"
      border
      @change="changeState(todoObj.id, todoObj.done)"
      ><span v-show="!todoObj.isEdit">{{ todoObj.name }}</span>
      <input
        type="text"
        :value="todoObj.name"
        v-show="todoObj.isEdit"
        @blur="finish(todoObj, $event)"
        ref="inputTitle"
      />
      <el-button
        size="mini"
        round
        class="change"
        @click="edit(todoObj)"
        v-show="!todoObj.isEdit"
        >编辑</el-button
      >
      <el-button
        type="danger"
        round
        size="mini"
        class="delete"
        @click="remove(todoObj.id)"
        >删除</el-button
      ></el-checkbox
    >
  </div>
</template>

<script>
import pubsub from "pubsub-js";
export default {
  name: "Item",
  props: ["todoObj", "ItemList"],
  data() {
    return {};
  },
  methods: {
    changeState(id, done) {
      // this.checkTodo(id);
      // console.log(id, !done);
      // this.$bus.$emit("checkTodo", id);
      pubsub.publish("checkTodo", id); // 发布消息
    },
    remove(id) {
      if (confirm("您确定要删除吗？")) {
        this.$bus.$emit("deleteTodo", id);
      }
    },
    edit(todoObj) {
      if (todoObj.hasOwnProperty("isEdit")) {
        todoObj.isEdit = true;
      } else {
        this.$set(todoObj, "isEdit", true);
      }
      // nextTick所指定的回调会在dom节点更新后执行
      this.$nextTick(function () {
        this.$refs.inputTitle.focus();
      });
    },
    finish(todoObj, e) {
      todoObj.isEdit = false;
      if (!e.target.value.trim()) return alert("输入不能为空");
      this.$bus.$emit("updateTodo", todoObj.id, e.target.value);
    },
  },
  mounted() {
    // console.log(this.todoObj);
  },
  updated() {
    // console.log(this.todoObj);
  },
};
</script>

<style lang='less' scoped>
.el-checkbox {
  width: 450px;
  margin: 0;
  display: block;
  text-align: left;
  margin: 10px;
  position: relative;
  .change {
    position: absolute;
    right: 80px;
    top: 5px;
    display: none;
  }
  .delete {
    position: absolute;
    right: 20px;
    top: 5px;
    display: none;
  }
}
.el-checkbox:hover {
  background-color: rgb(245, 245, 245);
}
.el-checkbox:hover button {
  display: block;
}
</style>